import { provide } from "vue";
import { WS_ADDRESS } from "../configs";
import store from "@/store";

export function useWebsocket(handleMessage) {
    const ws = new WebSocket(WS_ADDRESS);

    const init = () => {
        bindEvent();
    }

    function bindEvent() {
        ws.addEventListener('open', handleOpen, false);
        ws.addEventListener('close', handleClose, false);
        ws.addEventListener('error', handleError, false);
        ws.addEventListener('message', handleMessage, false);
    }

    store.commit('setSocketState',true)
    function handleOpen(e) {
        console.log("Websocket open", e);
    }

    function handleClose(e) {
        console.log("Websocket close", e);
    }

    function handleError(e) {
        console.log("Websocket error", e);
        store.commit('setSocketState',false)
    }

    init();

    return ws;
}

export default useWebsocket;